package sxe.core.string;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import snobject.snObject;
import snobject.snObjectArgList;
import snobject.snString;
import step.EvaluationFailure;
import step.FunctionWrapper;
import step.exceptions.ResourceUnavailableException;

public class macroexpand extends FunctionWrapper {

	public static String MACRO_EVAL_COUNT = "$EVAL_COUNT$"; 
	public static String MACRO_TIME = "$NOW$";
	public static SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy\th:mm:ss a");

	private int evalct = 0;
	
	@Override
	public snObject Call(snObjectArgList argv) throws EvaluationFailure,
			ClassCastException, ArrayIndexOutOfBoundsException,
			ResourceUnavailableException {
		
		snString sn = argv.popString();

		String t = new String(sn.getString());
		
		if(t.contains(MACRO_EVAL_COUNT))
			if(expnode!=null)
				t = t.replace(MACRO_EVAL_COUNT, String.valueOf(expnode.EvaluationCount()));
			else
				t = t.replace(MACRO_EVAL_COUNT, String.valueOf(++evalct));
		
		if(t.contains(MACRO_TIME)){
			Calendar c = Calendar.getInstance();
			String sTimeInst = formatter.format(c.getTime());
			t = t.replace(MACRO_TIME,sTimeInst);
		}
		
		return new snString(t);		
	}

}
